// SmarTest Studio - WorkspaceTab类

import { showNotification } from './utils.js';
import { ProjectManager } from './project-manager.js';
import http from './http-client.js';

/**
 * WorkspaceTab类 - 负责管理工作区标签页的功能
 */
export class WorkspaceTab {
    constructor() {
        // 创建ProjectManager实例
        this.projectManager = new ProjectManager();
        
        // 绑定方法到实例
        this.loadProjects = this.loadProjects.bind(this);
        this.setupProjectWorkspaceFilters = this.setupProjectWorkspaceFilters.bind(this);
        this.newProject = this.newProject.bind(this);
        this.setupProjectButtons = this.setupProjectButtons.bind(this);
        this.renameProject = this.renameProject.bind(this);
        this.setProject = this.setProject.bind(this);
        this.runProject = this.runProject.bind(this);
        
        // 初始化ProjectManager
        this.projectManager.initProjectOperations(this.loadProjects);
    }
    
    /**
     * 设置项目工作区筛选功能
     */
    setupProjectWorkspaceFilters() {
        const searchInput = document.getElementById('projectSearchInput');
        const ownerFilter = document.getElementById('ownerFilter');
        const typeFilter = document.getElementById('typeFilter');
        const boardFilter = document.getElementById('boardFilter');
        const productFilter = document.getElementById('productFilter');
        const platformFilter = document.getElementById('platformFilter');
        const versionFilter = document.getElementById('versionFilter');
        const startDateFilter = document.getElementById('startDateFilter');
        const endDateFilter = document.getElementById('endDateFilter');

        const applyFilters = () => {
            const params = {};
            if (searchInput.value) params.search = searchInput.value;
            if (ownerFilter.value !== 'Owner') params.owner = ownerFilter.value;
            if (typeFilter.value !== 'Type') params.type = typeFilter.value;
            if (boardFilter.value!== 'Board') params.board = boardFilter.value;
            if (productFilter.value!== 'Product') params.product = productFilter.value;
            if (platformFilter.value !== 'Platform') params.platform = platformFilter.value;
            if (versionFilter.value) params.version = versionFilter.value;
            if (startDateFilter.value) params.start_date = startDateFilter.value;
            if (endDateFilter.value) params.end_date = endDateFilter.value;
            console.log('应用筛选条件:', params);
            this.loadProjects(params);
        };

        // 使用HomePage中的静态debounce方法
        const debouncedApplyFilters = this.constructor.debounce(applyFilters, 500); // 500ms debounce

        if (searchInput) {
            searchInput.addEventListener('input', debouncedApplyFilters);
            searchInput.addEventListener('keypress', (event) => {
                if (event.key === 'Enter') {
                    applyFilters(); // Apply immediately on Enter
                }
            });
        }
        if (versionFilter) {
            versionFilter.addEventListener('input', debouncedApplyFilters);
            versionFilter.addEventListener('keypress', (event) => {
                if (event.key === 'Enter') {
                    applyFilters(); // Apply immediately on Enter
                }
            });
        }
        // 确保所有过滤器元素都添加了change事件监听器
        const projectFilters = [
            searchInput,
            ownerFilter, 
            typeFilter, 
            boardFilter, 
            productFilter, 
            platformFilter, 
            versionFilter, 
            startDateFilter, 
            endDateFilter];
        projectFilters.forEach(filterElement => {
            if (filterElement) {
                // 移除可能存在的旧事件监听器
                filterElement.removeEventListener('change', applyFilters);
                // 添加新的事件监听器
                filterElement.addEventListener('change', applyFilters);
                console.log('已为元素添加事件监听器:', filterElement.id);
            } else {
                console.warn('过滤器元素不存在:', filterElement);
            }
        });
    }
    
    /**
     * 加载项目列表
     * @param {Object} filters - 筛选条件
     */
    loadProjects(filters = {}) {
        let url = '/api/projects?api=load_projects';
        const queryParams = new URLSearchParams(filters).toString();
        if (queryParams) {
            url += '&' + queryParams;
        }

        http.get(url)
            .then((response) => {
                const projects = response.data;
                const tableBody = document.getElementById('projectsTable');
                tableBody.innerHTML = '';

                projects.forEach((project) => {
                    const row = document.createElement('tr');
                    // 添加data-project-id属性到行元素，用于项目选择功能
                    row.setAttribute('data-project-name', project.name);
                    row.setAttribute('data-project-owner', project.owner);
                    // 在loadProjects函数中修改按钮HTML生成部分
                    row.innerHTML = `
                        <td>${project.name}</td>
                        <td>${project.owner}</td>
                        <td>${project.type}</td>
                        <td>${project.board}</td>
                        <td>${project.product}</td>
                        <td>${project.platform}</td>
                        <td>${project.version}</td>
                        <td>${project.created}</td>
                        <td>${project.updated}</td>
                        <td>${project.published}</td>
                        <td>${project.description}</td>
                        <!--
                        <td>
                            <span class="status-badge ${this.getStatusClass(project.status)}">${project.status}</span>
                        </td>
                        -->
                        <td>
                            <div class="btn-group">
                                <button class="btn btn-sm btn-outline-primary rename-project-btn" title="重命名" data-project-name="${project.name}" data-project-owner="${project.owner}">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-secondary open-project-btn" title="打开" data-project-name="${project.name}" data-project-owner="${project.owner}">
                                    <i class="bi bi-folder2-open"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-info set-project-btn" title="设置" data-project-name="${project.name}" data-project-owner="${project.owner}">
                                    <i class="bi bi-gear"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-success run-project-btn" title="运行" data-project-name="${project.name}" data-project-owner="${project.owner}">
                                    <i class="bi bi-play"></i>
                                </button>
                            </div>
                        </td>
                    `;
                    tableBody.appendChild(row);
                });
                
                // 为项目名称添加点击编辑功能
                this.setupProjectButtons();
            })
            .catch((error) => {
                console.error('加载项目失败:', error);
                showNotification('加载项目失败', 'danger');
            });
    }
    
    /**
     * 创建新项目
     */
    newProject() {
        // 显示模态框
        var newProjectModal = new bootstrap.Modal(document.getElementById('newProjectModal'));
        newProjectModal.show();

        // 处理确认按钮点击事件
        document.getElementById('createProjectBtn').addEventListener('click', () => {
            var projectName = document.getElementById('projectName').value;
            var projectType = document.getElementById('projectType').value;
            var projectBoard = document.getElementById('projectBoard').value;
            var projectProduct = document.getElementById('projectProduct').value;
            var projectPlatform = document.getElementById('projectPlatform').value;
            var projectVersion = document.getElementById('projectVersion').value;
            var projectDescription = document.getElementById('projectDescription').value;
        
            if (projectName && projectType && projectBoard && projectProduct && projectPlatform && projectVersion && projectDescription) {
                // 构建POST请求数据
                var postData = {
                    api: 'new_project',
                    name: projectName,
                    type: projectType,
                    board: projectBoard,
                    product: projectProduct,
                    platform: projectPlatform,
                    version: projectVersion,
                    description: projectDescription,
                };
                // 发送POST请求创建新项目
                http.post('/api/projects', postData)
                    .then((response) => {
                        // 隐藏模态框
                        newProjectModal.hide();
                        this.loadProjects();
                        showNotification('项目创建成功', 'success');
                    })
                    .catch((error) => {
                        console.error('创建项目失败:', error);
                        showNotification('创建项目失败', 'danger');
                    });
            } else {
                alert('请填写所有字段');
            }
        });
    }
    
    /**
     * 设置项目操作按钮事件处理
     */
    setupProjectButtons() {
        // 重命名按钮事件处理
        document.querySelectorAll('.rename-project-btn').forEach(button => {
            button.addEventListener('click', (event) => {
                const projectOwner = event.currentTarget.getAttribute('data-project-owner');
                const projectName = event.currentTarget.getAttribute('data-project-name');
                // rename project
                this.renameProject(projectOwner, projectName);
            });
        });

        // 打开按钮事件处理
        document.querySelectorAll('.open-project-btn').forEach(button => {
            button.addEventListener('click', (event) => {
                const projectOwner = event.currentTarget.getAttribute('data-project-owner');
                const projectName = event.currentTarget.getAttribute('data-project-name');
                // open project
                window.location.href = `/project/${encodeURIComponent(projectOwner)}/${encodeURIComponent(projectName)}`;
            });
        });

        // 设置按钮事件处理
        document.querySelectorAll('.set-project-btn').forEach(button => {
            button.addEventListener('click', (event) => {
                const projectOwner = event.currentTarget.getAttribute('data-project-owner');
                const projectName = event.currentTarget.getAttribute('data-project-name');
                // set project
                this.setProject(projectOwner, projectName);
            });
        });
        
        // 运行按钮事件处理
        document.querySelectorAll('.run-project-btn').forEach(button => {
            button.addEventListener('click', (event) => {
                const projectOwner = event.currentTarget.getAttribute('data-project-owner');
                const projectName = event.currentTarget.getAttribute('data-project-name');
                // run project
                this.runProject(projectOwner, projectName);
            });
        });
    }
    
    /**
     * 重命名项目函数
     * @param {string} projectOwner - 项目所有者
     * @param {string} projectName - 项目名称
     */
    renameProject(projectOwner, projectName) {
        // 找到对应的项目行
        const projectRow = document.querySelector(`tr[data-project-name="${projectName}"][data-project-owner="${projectOwner}"]`);
        if (!projectRow) {
            console.error('找不到项目行');
            return;
        }
        
        const nameCell = projectRow.querySelector('td:first-child');
        const originalName = nameCell.textContent;
        
        // 创建输入框替换项目名
        const input = document.createElement('input');
        input.type = 'text';
        input.value = originalName;
        input.className = 'form-control form-control-sm';
        input.style.width = '100%';
        
        nameCell.innerHTML = '';
        nameCell.appendChild(input);
        input.focus();
        input.select();
        
        // 处理输入完成
        const handleRename = () => {
            const newName = input.value.trim();
            
            if (newName === originalName || newName === '') {
                // 恢复原名字
                nameCell.textContent = originalName;
                return;
            }
            
            // 发送重命名请求
            http.post('/api/projects', {
                api: 'rename_project',
                old_name: originalName,
                new_name: newName,
                owner: projectOwner
            })
            .then(() => {
                // 更新项目名
                nameCell.textContent = newName;
                projectRow.setAttribute('data-project-name', newName);
                // 更新按钮的data属性
                projectRow.querySelectorAll('[data-project-name]').forEach(btn => {
                    btn.setAttribute('data-project-name', newName);
                });
                showNotification('项目重命名成功', 'success');
            })
            .catch(error => {
                nameCell.textContent = originalName;
                showNotification('项目重命名失败: ' + error.message, 'danger');
            });
        };
        
        // 监听回车和失焦事件
        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                handleRename();
            }
        });
        
        input.addEventListener('blur', handleRename);
    }
    
    /**
     * 设置项目函数
     * @param {string} projectOwner - 项目所有者
     * @param {string} projectName - 项目名称
     */
    setProject(projectOwner, projectName) {
        // 创建设置模态框
        const modalHtml = `
            <div class="modal fade" id="projectSettingsModal" tabindex="-1">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">项目设置 - ${projectName}</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <form id="projectSettingsForm">
                                <div class="mb-3">
                                    <label for="projectDescription" class="form-label">项目描述</label>
                                    <textarea class="form-control" id="projectDescription" rows="3"></textarea>
                                </div>
                                <div class="mb-3">
                                    <label for="projectType" class="form-label">项目类型</label>
                                    <select class="form-select" id="projectType">
                                        <option value="web">Web应用</option>
                                        <option value="mobile">移动应用</option>
                                        <option value="desktop">桌面应用</option>
                                        <option value="api">UiTest服务</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label for="projectPlatform" class="form-label">目标平台</label>
                                    <select class="form-select" id="projectPlatform">
                                        <option value="android">Android</option>
                                        <option value="ios">iOS</option>
                                        <option value="web">Web</option>
                                        <option value="windows">Windows</option>
                                        <option value="linux">Linux</option>
                                        <option value="macos">macOS</option>
                                    </select>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" id="saveProjectSettings">保存设置</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 移除已存在的模态框
        const existingModal = document.getElementById('projectSettingsModal');
        if (existingModal) {
            existingModal.remove();
        }
        
        // 添加模态框到页面
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('projectSettingsModal'));
        modal.show();
        
        // 保存设置按钮事件
        document.getElementById('saveProjectSettings').addEventListener('click', () => {
            const description = document.getElementById('projectDescription').value;
            const type = document.getElementById('projectType').value;
            const platform = document.getElementById('projectPlatform').value;
            
            http.post('/api/projects', {
                api: 'set_project',
                name: projectName,
                owner: projectOwner,
                settings: {
                    description: description,
                    type: type,
                    platform: platform
                }
            })
            .then(response => {
                if (response.data.success) {
                    showNotification('项目设置保存成功', 'success');
                    modal.hide();
                    // 重新加载项目列表以显示更新
                    this.loadProjects();
                } else {
                    showNotification('保存项目设置失败: ' + (response.data.message || '未知错误'), 'danger');
                }
            })
            .catch(error => {
                showNotification('保存项目设置失败: ' + error.message, 'danger');
            });
        });
        
        // 模态框关闭时清理
        document.getElementById('projectSettingsModal').addEventListener('hidden.bs.modal', () => {
            document.getElementById('projectSettingsModal').remove();
        });
    }
    
    /**
     * 运行项目函数
     * @param {string} projectOwner - 项目所有者
     * @param {string} projectName - 项目名称
     */
    runProject(projectOwner, projectName) {
        http.post('/api/projects', {
            api: 'run_project',
            name: projectName,
            owner: projectOwner
        })
        .then(response => {
            if (response.data.success) {
                showNotification('项目运行请求已发送', 'success');
                // 可以在这里添加运行状态的实时更新逻辑
            } else {
                showNotification('运行项目失败: ' + (response.data.message || '未知错误'), 'danger');
            }
        })
        .catch(error => {
            showNotification('运行项目失败: ' + error.message, 'danger');
        });
    }
    
    /**
     * 获取状态样式类
     * @param {string} status - 状态值
     * @returns {string} - 对应的CSS类名
     */
    getStatusClass(status) {
        switch (status) {
            case '活跃':
                return 'status-active';
            case '完成':
                return 'status-completed';
            case '暂停':
                return 'status-paused';
            default:
                return '';
        }
    }
    
    /**
     * 防抖函数
     * @param {Function} func - 要执行的函数
     * @param {number} delay - 延迟时间（毫秒）
     * @returns {Function} - 防抖处理后的函数
     */
    static debounce(func, delay) {
        let timeout;
        return function(...args) {
            const context = this;
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(context, args), delay);
        };
    }
}